package com.mvc.framework.listener;

import com.mvc.framework.entity.AnnotationBean;
import com.mvc.framework.utils.AnnotationConfig;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

public class AnnotationListener implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// 初始化，读取注解配置
		ServletContext context = sce.getServletContext();
		String xmlPath = context.getInitParameter("annotation-config");
		String tomcatPath = context.getRealPath("\\");
		System.out.println("开始加载mvc配置...");

		try {
			List<AnnotationBean> config = AnnotationConfig.readAnnotationXml(tomcatPath + xmlPath);
			context.setAttribute("mvcConfig", config);
			System.out.println("加载mvc配置完成");
		} catch (Exception e) {
			System.out.println("加载mvc配置发生异常");
			e.printStackTrace();
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		List<AnnotationBean> config = (List<AnnotationBean>) sce.getServletContext().getAttribute("mvcConfig");
		if (config != null) {
			config.clear();
			config = null;
			sce.getServletContext().setAttribute("mvcConfig", null);
		}
		System.out.println("信息：系统已注销！");
	}
}
